<script setup lang="ts">
import { defineAsyncComponent, shallowRef, watch } from 'vue';
import { useRoute } from 'vue-router';

const route = useRoute();
const sessionId = computed(() => route.params?.id);

// 优化：使用异步组件和智能预加载
const ChatDefaul = defineAsyncComponent(() =>
  import('@/pages/chat/layouts/chatDefaul/index.vue'),
);

const ChatWithId = defineAsyncComponent(() =>
  import('@/pages/chat/layouts/chatWithId/index.vue'),
);

// 智能预加载：当可能即将使用某个组件时预加载
const preloadComponents = shallowRef<Record<string, boolean>>({
  chatDefault: false,
  chatWithId: false,
});

// 监听路由变化，智能预加载可能需要的组件
watch(() => route.path, (newPath) => {
  // 如果当前在根路径或聊天页，预加载chatWithId
  if (newPath === '/' || newPath.startsWith('/chat')) {
    if (!preloadComponents.value.chatWithId) {
      preloadComponents.value.chatWithId = true;
      // 触发预加载
      import('@/pages/chat/layouts/chatWithId/index.vue');
    }
  }
}, { immediate: true });
</script>

<template>
  <div class="chat-container">
    <!-- 默认聊天页面 -->
    <ChatDefaul v-if="!sessionId" />
    <!-- 带id的聊天页面 -->
    <ChatWithId v-else />
  </div>
</template>

<style lang="scss" scoped>
.chat-container {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: calc(100% - 32px);
  height: 100%;
  padding: 0 16px;
  overflow-anchor: none;
}
@media (max-width: 768px) {
  .chat-container {
    display: block!important;
    padding: 4px!important;
    width: calc(100% - 8px)!important;
    height: calc(100% - 8px)!important;
  }
}
</style>
